var packageNames = ['com.ss.android.ugc.aweme', 'com.bbk.launcher2', 'org.autojs.autojs6', 'com.vivo.upslide'],
    top = null,
    back = null,
    kag = null,
    showLog = false, // 显示日志
    showArea = false, // 显示识别、点击区域
    jumpRecognize = false, // 跳过识别
    loopTime = 500,
    trySwipeUpCount = 0,
    loop = function () {
        showLog && console.log('\ncoming loop...')
        if (!packageNames.includes(currentPackage())) {
            clearInterval(interval);
            showLog && console.log('\n切换至 ' + currentPackage() + ' 脚本暂停');
            toast('脚本已暂停');
        }
        showLog && console.log('\ncheck package...');

        if (textStartsWith('上滑继续观看').exists()) { // 读秒广告
            swipeUp();
        }

        if (desc('进度条').exists() || id('eg7').exists() || text('免费看全集').exists()) { // 页面有效元素
            trySwipeUpCount = 0; // 重置尝试滑动次数
        } else { // 页面中没有任何有效元素的话，判定为站内广告
            swipeUp();
            trySwipeUpCount++; // 尝试滑动次数
            if (trySwipeUpCount >= 2) {
                desc('进度条').waitFor(); // 阻塞，等待进度条出现，避免无效的循环
            }
        }

        // 监听是否快进入下一个视频
        if (recognizeNextVideo() && !jumpRecognize) {
            showLog && console.log('\nnext video...');
            let currentEp = currentEpisode(),
                nextEp = currentEp + 1,
                tk = id('t_k').findOnce();
            // 展开选集
            if (tk == null) return false;
            tk.click();
            // 等待完全展开
            sleep(2500);

            var recognizeResult = recognizeNode(),
                firstEp = recognizeResult.recognizeText.replace(/\D/g, '') * 1,
                childCount = recognizeResult.recycler.childCount(),
                maxEp = firstEp + (childCount - 1);
            if (nextEp >= firstEp && nextEp <= maxEp) { // 下一集存在，自动切入下一集
                let indexNode = (childCount - 1) - (maxEp - nextEp);
                let nodeItem = recognizeResult.recycler.child(indexNode).child(0);
                showHighlight(nodeItem.bounds().left, nodeItem.bounds().top, nodeItem.boundsWidth(), nodeItem.boundsHeight(), 2000);
                let clickX = device.width / 2, clickY = nodeItem.bounds().top + (nodeItem.boundsHeight() / 2);
                showLog && console.log('\ncep: ' + currentEp + ', mep: ' + maxEp + ', index: ' + indexNode + ', clickX: ' + clickX + ', clickY: ' + clickY);
                clickWithHighlight(clickX, clickY);
                sleep(10 * 1000); // 阻塞 10 秒循环，减轻循环压力
            } else { // 下一集不存在，滑动加载更多
                toast('下一集未找到...');
                sleep(2000);
                click(top.boundsCenterX(), top.boundsCenterY());
                sleep(1500);
                swipeUp();
            }
        }
    }, interval;

if (currentPackage() != packageNames[0]) {
    auto.waitFor(); // 获取无障碍服务权限，实现 Swipe 方法的关键
    images.requestScreenCapture(); // 获取截图权限，实现 OCR 识别的关键
    let hg = launch(packageNames[0]);
    if (hg) {
        toast('启动中...');
        sleep(2000);

        showLog && console.show();
        interval = setInterval(loop, loopTime);
    } else {
        toast('启动失败');
    }
}

function showHighlight(x, y, w, h, duration = 800) {
    if (!showArea) return;
    let floatWindow = floaty.rawWindow(
        <frame gravity="center" bg='#FF0000'></frame>
    );
    if (top != null) {
        y -= top.bounds().top;
    }
    floatWindow.setTouchable(false);
    floatWindow.setSize(w, h);
    floatWindow.setPosition(x, y);
    setTimeout(() => {
        floatWindow.close();
    }, duration);
}

function clickWithHighlight(x, y, duration = 800) {
    let size = 20, radius = size / 2;
    showHighlight(x - radius, y - radius, size, size, duration);
    click(x, y);
}

function swipeUp() {
    swipe(device.width / 2, device.height * 3 / 4, device.width / 2, device.height / 4, 500);
}

function recognizeNextVideo() {
    var startTime = new Date().getTime();
    showLog && console.log('\nrecognize start...');
    if (id('back_btn').exists()) {
        if (back == null) { // 首次定位
            top = id('juo').findOnce();
            back = id('back_btn').findOnce();
            kag = id('kag').findOnce();
        }
    } else {
        return false;
    }
    // 未进入合集则退出
    if (top == null || back == null || kag == null) return false;
    let topBounds = top.bounds(),
        backBounds = back.bounds(),
        kagBounds = kag.bounds();

    // top 的宽高
    let width = topBounds.right - topBounds.left,
        height = topBounds.bottom - topBounds.top;
    // 去除两边按钮的宽度
    width -= backBounds.right + (top.boundsWidth() - kagBounds.left);
    showLog && console.log('\ncalculate bounds...');

    let img = images.captureScreen();
    let area = [backBounds.right, topBounds.top, width, height];
    let texts = ocr.recognizeText(img, area);
    showHighlight(area[0], area[1], area[2], area[3], 500);
    showLog && console.log('\nrecognize end...', texts);
    var endTime = new Date().getTime();
    console.log('\ntask duration ' + (endTime - startTime) + ' ms');
    return texts.filter(text => text.includes('下一个视频')).length > 0;
}

function recognizeNode() {
    let recycler = className('androidx.recyclerview.widget.RecyclerView').findOnce();
    let group = recycler.child(0), item = group.child(0), node = item.child(1);
    let bounds = node.bounds();
    let img = images.captureScreen();
    return {
        recognizeText: ocr.recognizeText(img, [bounds.left, bounds.top, bounds.right - bounds.left, bounds.bottom - bounds.top])[0],
        recycler: recycler
    }
}

function currentEpisode() {
    var regex = /^第\d+集/, views = textMatch(regex).find(),
        episodes = views.map(view => view.text().match(regex)[0].replace(/\D/g, '') * 1);
    if (episodes.length >= 3) {
        return episodes[1];
    } else {
        if (episodes[0] != 2) {
            return episodes.reduce((prev, next) => Math.max(prev, next));
        } else {
            return episodes[0];
        }
    }
}
